package com.yamaha.bikedesalon.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

public class CacheManager {
	private static Activity ACTIVITY;
	private static final Map<String, Bitmap> image = new HashMap<String, Bitmap>();
	private static final Map<String, String> cache = new HashMap<String, String>();

	public static final String FACEBOOK_USER_ID = "fbUserId";
	public static final String FACEBOOK_USER_EMAIL = "fbUserEmail";
	public static final String USER_NAME = "userName";
	public static final String USER_PROFILE_IMAGE = "userProfileImage";
	public static final String USER_LAST_LOGIN = "userLastLogin";
	public static final String USER_STATUS = "userStatus";

	private final static CacheManager instance = new CacheManager();

	private CacheManager() {

	}

	public static CacheManager getInstance(final Activity activity) {
		CacheManager.ACTIVITY = activity;
		return instance;
	}

	// public void setActivity(final Activity activity) {
	// CacheManager.ACTIVITY = activity;
	// LOADER = ImageLoader.getInstance();
	// LOADER.init(ImageLoaderConfiguration.createDefault(ACTIVITY));
	// }

	public String get(final String str) {
		final String name = Base64.encodeToString(str.getBytes(),
				Base64.DEFAULT);

		if (null != cache.get(name)) {
			Log.d("CacheManager", "Load From Cache. " + str);
			return cache.get(name);
		}

		try {
			final File file = ACTIVITY.getBaseContext().getFileStreamPath(name);

			if (!file.exists()) {
				// throw new FileNotFoundException();
				return null;
			}

			final Date date = new Date();

			if (!file.canRead() && !file.canWrite()) {
				// throw new Exception("File cannot be created.");
				return null;
			}

			final FileInputStream fi = ACTIVITY.getBaseContext().openFileInput(
					name);

			StringBuffer fileContent = new StringBuffer("");

			byte[] buffer = new byte[1024];
			int length = 0;
			while ((length = fi.read(buffer)) != -1) {
				fileContent.append(new String(buffer));
			}
			fi.close();

			final JSONObject obj = new JSONObject(fileContent.toString());
			final long time = obj.getLong("time");
			final double days = obj.getDouble("days");

			if (date.getTime() - time >= (days * 1000 * 60 * 60 * 24)) {
				throw new Exception("File was expired.");
			}

			Log.d("CacheManager", "Load From Cache File.");
			return obj.getString("data");

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public void put(final String str, final String obj, final double days) {
		final String name = Base64.encodeToString(str.getBytes(),
				Base64.DEFAULT);

		// Put to Map
		cache.put(name, obj);

		try {
			final File file = ACTIVITY.getBaseContext().getFileStreamPath(name);
			if (file.exists()) {
				final String data = get(str);
				if (data.equals(obj)) {
					return;
				}
			}

			final JSONObject object = new JSONObject();
			object.put("time", Calendar.getInstance().getTimeInMillis());
			object.put("days", Double.toString(days));
			object.put("data", obj);

			final FileOutputStream fo = ACTIVITY.getBaseContext()
					.openFileOutput(name, Context.MODE_PRIVATE);
			fo.write(object.toString().getBytes());
			fo.close();
		} catch (Exception e) {
			Log.e("CacheManager", e.getMessage(), e);
		}

	}

	public Bitmap getBitmap(final String str) {
		final String name = Base64.encodeToString(str.getBytes(),
				Base64.DEFAULT);

		if (null != image.get(name)) {
			return image.get(name);
		}

		try {
			final FileInputStream fi = ACTIVITY.getBaseContext().openFileInput(
					name);

			return BitmapFactory.decodeFileDescriptor(fi.getFD());
		} catch (Exception e) {
			// Ignore Exception
		}

		return null;
	}

	public void putBitMap(final String str, final Bitmap bitmap) {
		final String name = Base64.encodeToString(str.getBytes(),
				Base64.DEFAULT);

		final Bitmap preBitmap = image.put(name, bitmap);

		if (null == preBitmap) {
			try {
				final FileOutputStream fo = ACTIVITY.getBaseContext()
						.openFileOutput(name, Context.MODE_PRIVATE);
				bitmap.compress(CompressFormat.PNG, 100, fo);
				fo.close();
			} catch (Exception e) {
				// Ignore Exception
			}

		}
	}

}
